/*
 * GetCart.java
 *
 * Created on 9 janvier 2008, 16:08
 */
package com.reimscopie.console ;

import javax.naming.* ;
import javax.transaction.* ;

import com.reimscopie.* ;
import com.reimscopie.beans.interfaces.* ;


/**
 * Display the user cart.
 */
class GetCart extends TransactionCommand {
  
  /**
   * Create a new instance of <code>GetCart</code>.
   */
  GetCart() {
    
  }
  
  
  /**
   * Return the name of this command. The name is the first word in the shell
   * command line.
   * 
   * @return The command name.
   */
  @Override
  public String getName() {
    return "get-cart" ;
  }
  

  /**
   * Return a short help message about this command.
   * 
   * @return The command help.
   */
  @Override
  public String getHelp() {
    return "Display the user cart" ;
  }
  

  /**
   * Return the command usage. This string must give all command options with
   * a description for each option.
   * 
   * @return The command usage.
   */
  @Override
  public String getUsage() {
    return "get-cart" ;
  }
  
  
  /**
   * Execute this command.
   * 
   * @param args The arguments given in the command line.
   * @param output The command output.
   * @exception CommandException The command failed.
   */
  @Override
  public void execute(String[] args,ConsoleOutput output)
  throws CommandException {
    
    // user bean
    ReimsCopieUserRemote bean = (ReimsCopieUserRemote)getVariable("user.bean") ;
    if (bean == null) {
      output.printError("not logged in",true) ;
      return ;
    }
    
    try {
      // get JNDI initial context
      InitialContext context      = new InitialContext() ;
      UserTransaction transaction = getTransaction(context) ;
      
      try {
        transaction.begin() ;
        
        float price = bean.getCartPrice() ;
        output.print("Cart price: "+price,true) ;
        
        Purchase[] purchases = bean.getCart() ;
        for (Purchase purchase : purchases) {
          output.print('-') ;
          output.print(purchase.toString()) ;
          output.println() ;
        }
        
        transaction.commit() ;
        output.print("Done",true) ;
      }
      catch (Exception e) {
        output.printError("Failed",true) ;
        try {
          transaction.rollback() ;
        }
        catch (SystemException ex) {
          output.printError(ex) ;
        }
        output.printError(e) ;
      }
    }
    catch (NamingException e) {
      output.printError("Cannot get initial context for JNDI") ;
      output.printError(e) ;
      return ;
    }
    
  }
  
}
